/**
 * [gulp 前端开发环境   1->开发环境（port->3000），2->生产环境（port->3030）]
 */
var fs = require('fs');
var babel = require("gulp-babel");//es6=>es5
var gulp = require('gulp'),
    header = require('gulp-header'),
    concat = require('gulp-concat'), //- 多个文件合并为一个；
    cleanCSS = require('gulp-clean-css'), //- 压缩CSS为一行；
    ugLify = require('gulp-uglify'), //压缩js
    imageMin = require('gulp-imagemin'), //压缩图片
    pngquant = require('imagemin-pngquant'), // 深度压缩
    htmlMin = require('gulp-htmlmin'), //压缩html
    changed = require('gulp-changed'), //检查改变状态
    sass = require('gulp-sass'), //压缩合并sass
    autoprefixer = require('gulp-autoprefixer'), //css前缀
    sourcemaps = require('gulp-sourcemaps'), //map跟踪文件
    del = require('del'),
    browserSync = require("browser-sync").create(); //浏览器实时刷新

    var pkg = require('./package.json');
    var banner = ['/**',
      ' * @description <%= pkg.name %> - <%= pkg.description %>',
      ' * @version v<%= pkg.version %>',
      ' * @author <%= pkg.author %>',
      ' * @date  <%= new Date().getFullYear()+"-"+(new Date().getMonth()+1)+"-"+new Date().getDate() %>',
      ' */',
      ''].join('\n');

      
/**
 * 开发环境
 */

// 监听文件变化
gulp.task('watch', function () {
    gulp.watch('src/**/*.js').on('change', function () {
        gulp.start('devscript');
        browserSync.reload();
    });
    gulp.watch('src/**/*.scss').on('change', function () {
        gulp.start('scss');
        browserSync.reload();
    });
    gulp.watch('src/**/*.html').on('change', function () {
        gulp.start('html');
        browserSync.reload();
    });
});

//编译环境dev
gulp.task('environmentdev', function () {
    fs.readFile('src/environment/environment.dev.js', 'utf-8', function (err, data) {
        if (err) {
            console.log(err);
        } else {
            fs.writeFile("src/environment/environment.js", data, function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('________开发(dev))环境已打包________');
                }
            })
        }
    });
})

gulp.task("devscript", function () {
    //dev
    gulp.src(['src/center/**/*.js'])
        .pipe(sourcemaps.init({ loadMaps: true }))
        // .pipe(babel())
        // .pipe(ugLify())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest('dist/center'))

    //copy lib 所以文件到dist
    gulp.src(['src/lib/**/*'])
        .pipe(gulp.dest('dist/lib'))

    gulp.src(['src/environment/*'])
        .pipe(gulp.dest('dist/environment'))

});

gulp.task('devimages', function () {

    gulp.src(['src/lib/assets/images*.*'])
        .pipe(gulp.dest('dist/lib/assets/images'))

});

gulp.task('dev', ['delete', 'environmentdev'], function () {

    gulp.start('devscript', 'scss', 'html', 'devimages', 'watch');

    browserSync.init({
        port: 3000,
        server: {
            baseDir: ['dist']
        }
    });

});



/**
 * 生产环境
 */
//压缩html
gulp.task('html', function () {
    var options = {
        removeComments: true, //清除HTML注释
        collapseWhitespace: true, //压缩HTML
        collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input />
        removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
        removeScriptTypeAttributes: true, //删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
        minifyJS: true, //压缩页面JS
        minifyCSS: true //压缩页面CSS
    };
    gulp.src('src/**/*.html')
        .pipe(htmlMin(options))
        .pipe(gulp.dest('dist'))
});

// 监听文件变化
gulp.task('watchProd', function () {
    gulp.watch('src/**/*.js').on('change', function () {
        gulp.start('script', 'scss', 'html', 'images');
        browserSync.reload();
    });
    gulp.watch('src/**/*.scss').on('change', function () {
        gulp.start('script', 'scss', 'html', 'mages');
        browserSync.reload();
    });
    gulp.watch('src/**/*.html').on('change', function () {
        gulp.start('script', 'scss', 'html', 'images');
        browserSync.reload();
    });
});

//压缩js
gulp.task("script", function () {
    //prod
    gulp.src(['src/center/*.js'])
        .pipe(babel())
        .pipe(ugLify())
        .pipe(header(banner, { pkg : pkg } ))
        .pipe(gulp.dest('dist'));

    //copy lib 所以文件到dist
    gulp.src(['src/lib/**/*'])
    .pipe(gulp.dest('dist/lib'))

});

//编译scss
gulp.task('scss', function () {
    gulp.src(['src/center/**/*.scss','src/center/**/*.css'])
        .pipe(sass())
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(cleanCSS())
        .pipe(header(banner, { pkg : pkg } ))
        .pipe(gulp.dest('dist/center'));
});

// 压缩图片
gulp.task('images', function () {

    gulp.src(['src/lib/assets/images/*.*'])
        .pipe(changed('dist', { hasChanged: changed.compareSha1Digest }))
        .pipe(imageMin({
            progressive: true, // 无损压缩JPG图片
            svgoPlugins: [{ removeViewBox: false }], // 不移除svg的viewbox属性
            use: [pngquant()] // 使用pngquant插件进行深度压缩
        }))
        .pipe(gulp.dest('dist/lib/assets/images'))

});


//删除dist下的所有文件
gulp.task('delete', function (cb) {
    return del(['dist'], cb);
})

//编译环境
gulp.task('environmentprod', function () {
    fs.readFile('src/environment/environment.prod.js', 'utf-8', function (err, data) {
        if (err) {
            console.log(err);
        } else {
            fs.writeFile("src/environment/environment.js", data, function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log('________生产(prod)环境已打包________');
                }
            })
        }
    });
})

//生产环境
gulp.task('build', ['delete', 'environmentprod'], function () {

    gulp.start('script', 'scss', 'html', 'images','watchProd');

    browserSync.init({
        port: 3000,
        server: {
            baseDir: ['dist']
        }
    });

});


// build->正式环境  dev->开发环境
// gulp.task('default', ['build']);
gulp.task('default', ['dev']);
